#ifndef GLWIDGET_H
#define GLWIDGET_H

#include "scene.h"
#include "opengl_device.h"
#include "camera_control_device.h"

#include <QGLWidget>
#include <QMouseEvent>
#include <QWheelEvent>

class GLWidget : public QGLWidget, public OpenGLDevice
{
  Q_OBJECT
  
public:
  GLWidget(Controller& c, QGLContext* context, QGLWidget *parent = 0) : QGLWidget(context, parent), OpenGLDevice(c), is_rotating(false)
  {
    setCursor(Qt::CrossCursor);
  }
  ~GLWidget() {}
protected:
  void initializeGL()
  {
    OpenGLDevice::init();
  }
  void init()
  {
    initializeGL();
  }

  void resizeGL(int w, int h)
  {
    OpenGLDevice::resize(w,h);
  }

  void paintGL()
  {
    OpenGLDevice::redraw();
  }

  void mouseMoveEvent ( QMouseEvent * event )
  {
    if (is_rotating)
    {
      setCursor(Qt::ClosedHandCursor);
      int dx = event->x() - lastMousePos.x();
      int dy = event->y() - lastMousePos.y();
      lastMousePos = screen_pos_type(event->x(), event->y(), 0.0);
      rotateCamera(dx, dy);
    }
    QWidget::mouseMoveEvent(event);
  }
  void mousePressEvent(QMouseEvent* event)
  {
    if (event->button() == Qt::LeftButton)
    {
      is_rotating = true;
      pressMousePos = lastMousePos = screen_pos_type(event->x(), event->y(), 0.0);
    }
    QWidget::mousePressEvent(event);
  }
  void mouseReleaseEvent(QMouseEvent* event)
  {
    if (event->button() == Qt::LeftButton)
    {
      lastMousePos = screen_pos_type(event->x(), event->y(), 0.0);
      is_rotating = false;
      setCursor(Qt::CrossCursor);
      if ((lastMousePos - pressMousePos).length() < 3) // click event
      {
        pickingEvent(lastMousePos);
      }
    }
    QWidget::mouseReleaseEvent(event);
  }
  void wheelEvent(QWheelEvent* event)
  {
    if (event->orientation() == Qt::Vertical)
    {
      zoomCamera(event->delta()/120.0); // magic value returned by my mouse per 1 step
    }
    QWidget::wheelEvent(event);
  }

public:
  void resize(unsigned int w, unsigned int h)
  {
    QGLWidget::resize(w, h);
  }
  void resize(int w, int h)
  {
    QGLWidget::resize(w, h);
  }
  void redraw()
  {
    update();
  }

  void update()
  {
    QGLWidget::update();
  }
private:
  screen_pos_type lastMousePos, pressMousePos;
  bool is_rotating;
};

#endif // GLWIDGET_H
